package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.config.ThreadLocalSession;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.service.ISystemConfigService;
import com.yiboshi.rehrs.domain.service.impl.SystemConfigServiceImpl;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.exception.ZyantExceptionUtils;
import com.yiboshi.rehrs.feign.PosterFeignInterceptor;
import com.yiboshi.rehrs.util.*;
import feign.codec.DecodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author jack 2025/4/5
 */
@Component
@Slf4j
public class HttpHelper {

    @Autowired
    ProxyHelper proxyHelper;

    @Autowired
    ZhongConfigHelper zhongConfigHelper;

    @Autowired
    HelperDaxiang helperDaxiang;

    @Autowired
    HelperJinshe helperJinshe;

    @Autowired
    RedisHelper redisHelper;

    @Autowired
    ISystemConfigService systemConfigService;


    public static String zy_host = "http://211.156.197.65";

    public JSONObject sendPost(String uri,ZhongUser zhongUser, String bodyData) {
        byte[] bodyBytes = bodyData.getBytes(Charset.defaultCharset());
        return sendPost(uri,zhongUser,bodyBytes);
    }
    public JSONObject sendPost(String uri,ZhongUser zhongUser, JSONObject dataJSON) {
        byte[] bodyBytes = dataJSON.toJSONString().getBytes(Charset.defaultCharset());
        return sendPost(uri,zhongUser,bodyBytes);
    }

    public JSONObject sendOriginPost(String uri,ZhongUser zhongUser, JSONObject dataJSON) {
        byte[] bodyBytes = dataJSON.toJSONString().getBytes(Charset.defaultCharset());
        Map<String, String> headers = new HashMap<>();
        int i = 0;
        long timeoutMillis = uri.contains("findpdasignwaybillinfonew")
                            ||uri.contains("loginbyusrface")
                ?8000:2000;
        i =uri.contains("findpdasignwaybillinfonew")||uri.contains("loginbyusrface")?1:2;
        HelperZhong helperZhong = redisHelper.selectHelper(uri);
        //helperZhong = helperDaxiang;
        Map<String, String> channelHeader = helperZhong.channelHeader(uri,zhongUser);
        if(CollUtil.isEmpty(channelHeader)){
            throw new ZhongException("E30000","授权异常mode="+helperZhong.getMode());
        }
        headers.putAll(headerAll(uri, zhongUser));
        headers.putAll(channelHeader);
        PosterFeignInterceptor.jdptSign(headers,zhongUser);
        String zyHost = systemConfigService.getOne("zy_host").getConfigValue();
        OkHttpUtil okHttpUtil = new OkHttpUtil().url(zyHost + uri)
                .headers(headers)
                .post(bodyBytes)
                .retryCount(i)
                .timeoutMillis(timeoutMillis);
        //okHttpUtil .proxySupplier(() -> proxyHelper.one());
       /* String initIp = zhongUser.getInitIp();
        if(StrUtils.isNotBlank(initIp)){
            headers.put("X-Forwarded-For",zhongUser.getInitIp());
            headers.put("X-Real-IP",zhongUser.getInitIp());
        }*/
        if(!RehrsSystemConfig.isDev()|| ThreadLocalSession.isMode(0)){
            okHttpUtil .proxySupplier(() -> proxyHelper.one());
        }
        try{
            String execute =okHttpUtil
                    .execute();
            JSONObject jsonObject = JSONObject.parseObject(execute);
            extracted(jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error("",e);
            throw  new RuntimeException(e.getMessage());
        }
    }
    public static void extracted(JSONObject res) {
        String obj = res.getString("obj");
        if (StrUtils.isBlank(obj)) {
            return;
        }
        if (obj.startsWith("{")) {
            res.put("obj", JSONObject.parseObject(obj));
        } else if (obj.startsWith("[")) {
            res.put("obj", JSONObject.parseArray(obj));
        } else {
            res.put("obj", obj);
        }
    }
    public JSONObject sendPost(String uri,ZhongUser zhongUser, byte[] bodyBytes,HelperZhong helperZhong){

        Map<String, String> headers = new HashMap<>();
        int i = 0;
        long timeoutMillis = uri.contains("findpdasignwaybillinfonew")
                   ||uri.contains("loginbyusrface")?8000:2000;
        i =uri.contains("findpdasignwaybillinfonew")||uri.contains("loginbyusrface")?1:2;
        try{
            if(helperZhong==null){
                helperZhong = redisHelper.selectHelper(uri);
            }

            //helperZhong = helperJinshe;
            //helperZhong = helperDaxiang;
            //log.info("mode:{},header获取,uri:{}",helperZhong.getMode(),uri);
            Map<String, String> channelHeader = helperZhong.channelHeader(uri,zhongUser);
            if(CollUtil.isEmpty(channelHeader)){
                throw new ZhongException("E30000","授权异常mode="+helperZhong.getMode());
            }
            headers.putAll(headerAll(uri, zhongUser));
            headers.putAll(channelHeader);
           /* if(StrUtils.isNotBlank(headers.get("android_id"))){
                headers.put("pda_id","");
            }*/

            //log.info("header,{}",JacksonUtils.toString(headers));
            //HttpResponse httpResponse = HttpClientUtils.doPostProxy(zy_host+uri, headers, bodyBytes, httpHost);

            String initIp = null;//CommonUtil.generateRandomIp();
            log.info("zy load initIp:{}, uri:{},",initIp,uri);
            if(StrUtils.isNotBlank(initIp)){
                headers.put("X-Forwarded-For",initIp);
                headers.put("X-Real-IP",initIp);
            }
            String zyHost = systemConfigService.getOne("zy_host").getConfigValue();
            OkHttpUtil okHttpUtil = new OkHttpUtil().url(zyHost + uri)

                    .post(bodyBytes)
                    .retryCount(i)
                    .timeoutMillis(timeoutMillis);
            //okHttpUtil .proxySupplier(() -> proxyHelper.one());
            if(!RehrsSystemConfig.isDev()){
                okHttpUtil .proxySupplier(() -> proxyHelper.one());
            }
            PosterFeignInterceptor.jdptSign(headers,zhongUser);
            String execute =okHttpUtil.headers(headers)
                    .execute();
            //List<JSONObject> list = JacksonUtils.toList(execute, JSONObject.class);
            //JacksonUtils.toBean(execute,J)
            JSONObject jsonObject = JSONObject.parseObject(execute);
            String code = jsonObject==null?"E30000":jsonObject.getString("resCode");
            if(jsonObject!=null){
                String msg = jsonObject.getString("msg");
                if(msg==null){
                    msg = "";
                }
                if(msg.contains("重新登录")||msg.contains("登录失败")){
                    throw new ZhongException(code,msg);
                }
                if(msg.contains("成功")){

                }else if(!Objects.equals(code,"A00001")){
                    log.error("mode:{} account:{} res:{}",helperZhong==null?"":helperZhong.getMode(),zhongUser.getAccount(),jsonObject);
                    throw new ZhongException(code,msg);
                }

            }
            return jsonObject;
        }catch (ZhongException e){
            //log.error("uri:{},msg:{}",uri,e.getMessage());
            throw  e;
        }catch (Exception e){
            log.error("mode:{} uri:{}",helperZhong.getMode(),uri,e);
            throw  new RuntimeException(e.getMessage());
        }
    }
    public JSONObject sendPost(String uri,ZhongUser zhongUser, byte[] bodyBytes) {
        return sendPost(uri,zhongUser,bodyBytes,null);
    }

    public Map<String,String> headerAll(String url, ZhongUser zhongUser){
        Map<String, String> fiddleMap = zhongConfigHelper.fiddleMap();
        if(url.contains("newCallAndFile")){
            fiddleMap.put("user-agent","okhttp/3.10.0");
            fiddleMap.put("content-type","application/x-www-form-urlencoded; charset=utf-8");
        }
        /*String padId = zhongUser.getPadId();
        if(StrUtils.isBlank(padId)){
            padId = zhongUser.getImei();
        }
         if(StrUtils.isNotBlank(padId)){
            fiddleMap.put("pda_id",padId);
        }else {
            fiddleMap.put("android_id", zhongUser.getAndroidId());
             fiddleMap.put("pda_id","");
        }*/
       /* String initIp = zhongUser.getInitIp();
        if(StrUtils.isNotBlank(initIp)){
            //stringMap1.put("X-Forwarded-For",zhongUser.getInitIp());
            //stringMap1.put("X-Real-IP",zhongUser.getInitIp());
        }
        fiddleMap.putAll(stringMap1);*/


        return fiddleMap;
    }

}
